package com.appinfo.controller.dev;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.appinfo.conts.AppConts;
import com.appinfo.entity.AppInfo;
import com.appinfo.entity.AppVersion;
import com.appinfo.entity.Category;
import com.appinfo.entity.DataDictionary;
import com.appinfo.entity.DevUser;
import com.appinfo.entity.vo.AppInfoSearchVo;
import com.appinfo.service.AppInfoService;
import com.appinfo.service.AppVersionService;
import com.appinfo.service.CategoryService;
import com.appinfo.service.DataDictionaryService;
import com.appinfo.util.Page;

@Controller
@RequestMapping("/dev/flatform/app")
public class DevAppInfoController {

	@Autowired
	AppInfoService appInfoSercice;

	@Autowired
	CategoryService categoryService;

	@Autowired
	DataDictionaryService dictionaryService;

	@Autowired
	AppVersionService appVersionService;
	
	@RequestMapping("/list")
	public String list(Model model, AppInfoSearchVo searchVo) {
		model.addAttribute("searchVo", searchVo);
		model.addAttribute("statusList", dictionaryService.selectByTypeCode(AppConts.APP_STATUS));
		model.addAttribute("flatFormList", dictionaryService.selectByTypeCode(AppConts.APP_FLATFORM));
		model.addAttribute("categoryLevel1List", categoryService.selectByParentId(0L));
		if (searchVo.getQueryCategoryLevel1() != null && searchVo.getQueryCategoryLevel1() != 0) {
			// 有1级菜单
			model.addAttribute("categoryLevel2List",
					categoryService.selectByParentId(searchVo.getQueryCategoryLevel1()));
		}
		if (searchVo.getQueryCategoryLevel2() != null && searchVo.getQueryCategoryLevel2() != 0) {
			// 有2级菜单
			model.addAttribute("categoryLevel3List",
					categoryService.selectByParentId(searchVo.getQueryCategoryLevel2()));
		}
		Page<AppInfo> pageInfo = appInfoSercice.selectByPage(searchVo);
		model.addAttribute("pages", pageInfo);
		model.addAttribute("appInfoList", pageInfo.getDataList());
		return "developer/appinfolist";
	}

	/**
	 * ajax获取分类
	 * 
	 * @param pid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/categorylevellist")
	public List<Category> categorylevellist(Long pid) {
		return categoryService.selectByParentId(pid);
	}

	/**
	 * ajax加载数据字典
	 * 
	 * @param tcode
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/datadictionarylist")
	public List<DataDictionary> datadictionarylist(String tcode) {
		return dictionaryService.selectByTypeCode(tcode);
	}

	@ResponseBody
	@RequestMapping("/apkexist")
	public Map<String, Object> apkexist(String APKName) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		
		if (!StringUtils.hasLength(APKName)) {
			resMap.put("APKName", "empty");
		}
		else{
			Boolean b = appInfoSercice.apkexist(APKName);
			if(b){
				resMap.put("APKName", "exist");
			}else{
				resMap.put("APKName", "noexist");
			}
		}
		return resMap;
	}

	// 跳转到添加
	@RequestMapping("/appinfoadd")
	public String toAdd() {
		return "developer/appinfoadd";
	}

	// 添加基础信息
	@RequestMapping("/appinfoaddsave")
	public String appinfoaddsave(AppInfo appinfo, MultipartFile a_logoPicPath, HttpSession session) {
		// 保存图片
		try {
			if (!a_logoPicPath.isEmpty()) {
				// 重命名
				String fileName = System.currentTimeMillis() + "_logo."
						+ FilenameUtils.getExtension(a_logoPicPath.getOriginalFilename());
				// 保存
				a_logoPicPath.transferTo(new File(AppConts.SAVE_FILE_PATH + fileName));

				// 设置数据库保存字段
				appinfo.setLogoPicPath("/appinfoSys/dev/flatform/app/showLogo?logoName=" + fileName);// 访问路径
				appinfo.setLogoLocPath(AppConts.SAVE_FILE_PATH + fileName);// 绝对路径
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 当前用户
		DevUser devUser = (DevUser) session.getAttribute("devUserSession");
		appinfo.setCreatedBy(devUser.getId());
		appinfo.setDevId(devUser.getId());

		boolean b = appInfoSercice.addAppInfo(appinfo);
		if (b) {
			// 去列表
			return "redirect:list";
		}
		return "appinfoaddsave";
	}

	/// appinfoSys/dev/flatform/app/showLogo?logoName=
	@RequestMapping("/showLogo")
	public void showImg(String logoName, HttpServletResponse response) {
		// 读取文件
		try {
			FileInputStream fis = new FileInputStream(AppConts.SAVE_FILE_PATH + logoName);
			byte[] bytes = new byte[fis.available()];
			fis.read(bytes);
			fis.close();
			response.getOutputStream().write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//版本
	@RequestMapping("/appversionadd")
	public String appversionadd(Long id,Model model){
		//查询app对应所有版本
		model.addAttribute("appId", id);
		model.addAttribute("appVersionList",appVersionService.selectAppVersionByAppId(id));
		return "developer/appversionadd";
	}
	//新增版本
	@RequestMapping("/addversionsave")
	public String addversionsave(AppVersion appVersion,
			MultipartFile a_downloadLink,
			Model model,HttpSession session){
		try {
			if(!a_downloadLink.isEmpty()){
//				a_downloadLink.getSize()  > 500 * 1024 * 1024
//				if(FilenameUtils.getExtension(a_downloadLink.getOriginalFilename().equals("apk"))
				// 重命名
				String fileName = System.currentTimeMillis() + "_apk."
						+ FilenameUtils.getExtension(a_downloadLink.getOriginalFilename());
				// 保存
				a_downloadLink.transferTo(new File(AppConts.SAVE_FILE_PATH + fileName));

				// 设置数据库保存字段
				appVersion.setDownloadLink("/appinfoSys/dev/flatform/app/download?appId="+appVersion.getAppId()+"&apkName=" + fileName);//下载链接
				appVersion.setApkLocPath(AppConts.SAVE_FILE_PATH + fileName);
				appVersion.setApkFileName(a_downloadLink.getOriginalFilename());
				
				//设置当前用户信息
				DevUser devUser = (DevUser) session.getAttribute("devUserSession");
				appVersion.setCreatedBy(devUser.getId());
				
				boolean b = appInfoSercice.addAppVersion(appVersion);
				
				if(b){
					return "redirect:list";
				}
			}else{
				model.addAttribute("fileUploadError", "文件不能为空");
			}
		} catch (Exception e) {
			model.addAttribute("fileUploadError", "文件上传失败");
			e.printStackTrace();
		}
		return "developer/appversionadd";
	}
	
	//下载
	@RequestMapping("/download")
	public void download(String apkName,Long appId,HttpServletResponse response){
		//更新下载次数
		
		//查询app信息
		
		//响应给用户
		response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
		response.setHeader("Content-Disposition","attachment;filename="+apkName);
		try {
			//读取文件输出到浏览器
			InputStream is = new FileInputStream(new File(AppConts.SAVE_FILE_PATH + apkName));
			OutputStream os = response.getOutputStream();
			IOUtils.copy(is, os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
